import axios from 'axios'
import config from '@/config'
import NProgress from 'nprogress'
import { useUserStore } from '@/store/userInfo'
const instance = axios.create({
  baseURL: config.baseApi,
})
instance.defaults.withCredentials = true //每次请求默认携带cookie
instance.interceptors.request.use((req) => {
  const userStore = useUserStore()
  const {cookie}=userStore
  // 进度条开始
  NProgress.start()
  // 每次请求添加一个时间戳参数
  if (req.method === 'get') {
    req.params = {
      ...req.data,
      cookie,
      timerstamp: Date.now(),
    }
  } else if (req.method === 'post') {
    req.params = {
      ...req.params,
      cookie,
      timerstamp: Date.now(),
    }
  }
  return req
})
instance.interceptors.response.use((res) => {
  // 进度条结束
  NProgress.done()
  return res.data
})
function request(options) {
  // 将get请求接收参数params换成data，便于api统一管理
  const method = options.method || 'get'
  if (method.toLowerCase() === 'get') {
    options.params = options.data
  }
  return instance(options)
}

export default request
